package cn.tiger.tigerAiAgent.controller;


import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatModel;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

@RestController
@RequestMapping("/dash-scope-chat-model")
public class DashScopeChatModelController {
    private final ChatModel dashScopeChatModel;

    private static final String DEFAULT_PROMPT = "";

    public DashScopeChatModelController(@Qualifier("dashscopeChatModel") ChatModel chatModel) {
        this.dashScopeChatModel = chatModel;
    }

    @GetMapping("/simple/chat")
    public String simpleChat(@RequestParam(value = "query", defaultValue = "你好，很高兴认识你，能简单介绍一下自己吗？") String query) {

        return dashScopeChatModel.call(new Prompt(query)).getResult().getOutput().getText();
    }

    /**
     * Stream 流式调用。可以使大模型的输出信息实现打字机效果。
     *
     * @return Flux<String> types.
     */
    @GetMapping("/stream/chat")
    public Flux<String> streamChat(@RequestParam(value = "query", defaultValue = "你好，很高兴认识你，能简单介绍一下自己吗？") String query,
                                   HttpServletResponse response) {

        // 避免返回乱码
        response.setCharacterEncoding("UTF-8");


        Flux<ChatResponse> stream = dashScopeChatModel.stream(new Prompt(query));
        return stream.map(resp -> resp.getResult().getOutput().getText());

    }
}
